package fun.ticsmyc.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import fun.ticsmyc.common.pojo.PageResult;
import fun.ticsmyc.common.utils.NumberUtils;
import fun.ticsmyc.item.mapper.UserMapper;
import fun.ticsmyc.item.pojo.User;
import fun.ticsmyc.item.utils.CodecUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Ticsmyc
 * @date 2020-05-02 21:40
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String KEY_PREFIX = "user:verify:";

    public User queryUserByid(Long userId) {
        System.out.println(userId);
        return this.userMapper.selectByPrimaryKey(userId);
    }

    public PageResult<User> queryAllUser(Integer page, Integer rows) {
        PageHelper.startPage(page,rows);
        List<User> users = this.userMapper.selectAll();
        PageInfo<User> pageInfo = new PageInfo<>(users);

        return new PageResult<>(users,pageInfo.getPages(),pageInfo.getTotal());
    }

    /**
     * 验证用户名是否已经被注册
     * @param username
     * @return
     */
    public Boolean checkUserName(String username) {
        User record = new User();
        record.setUsername(username);
        return this.userMapper.selectCount(record)==0;
    }

    /**
     * 验证码
     * @param email
     */
    public void getVerifyCode(String email) {
        if(StringUtils.isNotBlank(email)){
            // 1. 生成一个随机数作为验证码
            String code = NumberUtils.generateCode(6);
            // 2. 把这个随机数和用户邮箱存在redis中 ,10分钟有效
            stringRedisTemplate.opsForValue().set(KEY_PREFIX+email,code,10, TimeUnit.MINUTES);
            // 3. 向消息队列发送消息 ： 用户邮箱+验证码
                //创建消息内容
            Map<String,String> msg =  new HashMap<>();
            msg.put("email",email);
            msg.put("code",code);
            this.amqpTemplate.convertAndSend("XDMALL.SMS.EXCHANGE","sms.verify",msg);
        }
    }

    /**
     * 用户注册
     * @param user
     * @param code
     */
    public Boolean register(User user, String code) {
        // 1. 从redis中读取 用户邮箱+验证码 , 验证code 与验证码是否匹配
        String emailVerifyCode = stringRedisTemplate.opsForValue().get(KEY_PREFIX + user.getEmail());
        if(emailVerifyCode!=null && !emailVerifyCode.equals(code)){
            return false;
        }
        // 2. 生成salt值，user.setSalt 然后对用户的密码进行MD5加盐加密
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        user.setPassword( CodecUtils.md5Hex(user.getPassword(),salt));
        // 3. 把User插入数据库
        this.userMapper.insert(user);

        //向用户发送欢迎邮件
        Map<String,String> msg =  new HashMap<>();
        msg.put("email",user.getEmail());
        msg.put("name",user.getUsername());
        this.amqpTemplate.convertAndSend("XDMALL.SMS.EXCHANGE","sms.welcome",msg);

        //删除redis中缓存的验证码
        this.stringRedisTemplate.delete(KEY_PREFIX + user.getEmail());
        return true;
    }

    /**
     * 登陆校验
     * @param username
     * @param password
     * @return
     */
    public User loginCheck(String username, String password) {
        // 1. 根据username查用户信息
        User record = new User();
        record.setUsername(username);
        User user = this.userMapper.selectOne(record);
        if(user==null){
            return null;
        }
        // 2. 对用户传的password， 使用查到的用户信息中的salt进行MD5加盐加密  ，对比两个加密后的密码是否一致
        String spw = CodecUtils.md5Hex(password, user.getSalt());
        return StringUtils.equals(spw,user.getPassword())? user : null;
    }

    /**
     * 根据openid获取用户信息
     * @param openid
     * @return
     */
    public User wxLogin(String openid) {
        User rec = new User();
        rec.setOpenid(openid);
        return this.userMapper.selectOne(rec);
    }

    /**
     * 小程序端 保存用户信息
     * @param user
     * @return
     */
    public Boolean wxRegister(User user) {
        if(!checkUserName(user.getUsername())){
            return false;
        }
        this.userMapper.insert(user);
        //如果传来的数据中有邮箱，就发送邮件
        if(StringUtils.isNotBlank(user.getEmail())){
            //向用户发送欢迎邮件
            Map<String,String> msg =  new HashMap<>();
            msg.put("email",user.getEmail());
            msg.put("name",user.getUsername());
            this.amqpTemplate.convertAndSend("XDMALL.SMS.EXCHANGE","sms.welcome",msg);
        }
        return true;
    }


    /**
     * 小程序端修改用户信息
     * @param user
     */
    public void wxModifyData(User user) {
        Example example =new Example(User.class);
        //where 条件
        Example.Criteria criteria =example.createCriteria();
        criteria.andEqualTo("openid",user.getOpenid());
        this.userMapper.updateByExample(user,example);
    }
}
